﻿#region NeoPatterns
// 
// NeoPatterns framework is released under LGPLv3 license.
// See http://www.opensource.org/licenses/lgpl-3.0.html for more details.
// 
// Please visit http://neopatterns.wikidot.com for more information about NeoPatterns
// 
// Copyright (c) Pascal Craponne 2008
// 
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace NeoPatterns.Utility
{
    public static class TypeLoader
    {
        /// <summary>
        /// Loads a type, given a partially qualified name
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static Type GetType(string name)
        {
            // There is an anomaly in the .NET framework: when using accents in type names,
            // the type resolver loses them
            // so we use a local delegate which works on the paramter instead of event arguments
            ResolveEventHandler typeResolver = delegate
                                                   {
                                                       // try to load from within the current AppDomain
                                                       var assemblies = AppDomain.CurrentDomain.GetAssemblies();
                                                       foreach (var assembly in assemblies)
                                                       {
                                                           if (assembly.GetType(name) != null)
                                                               return assembly;
                                                       }
                                                       return null;
                                                   };
            try
            {
                AppDomain.CurrentDomain.TypeResolve += typeResolver;
                return Type.GetType(name);
            }
            finally
            {
                AppDomain.CurrentDomain.TypeResolve -= typeResolver;
            }
        }
    }
}
